package indi.jp.project.core.controller;

import indi.jp.project.core.entity.JsonResult;
import indi.jp.project.core.entity.Menu;
import indi.jp.project.core.service.MenuService;
import indi.jp.project.core.util.SimpleEntityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sys/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    private final SimpleEntityUtil<Menu> simpleEntityUtil = new SimpleEntityUtil<>();

//    @PreAuthorize("hasAuthority('sys:menu:query')")
    @GetMapping("/queryGrid")
    @ResponseBody
    public JsonResult queryGrid(@ModelAttribute Menu entity) {
        try {
            int offset = (entity.getPage() - 1) * entity.getPageSize();
            entity.setOffset(offset);
            Map<String, Object> map = menuService.queryGrid(entity);
            return JsonResult.success(map);
        } catch (SQLException e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    //    @PreAuthorize("hasAuthority('sys:menu:save')")
    @PostMapping("/save")
    @ResponseBody
    public JsonResult sava(@RequestBody Menu entity, HttpServletRequest request) {
        entity = simpleEntityUtil.setBaseEntity(entity, request);
        try {
            return menuService.save(entity);
        } catch (SQLException e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    @PostMapping("/deleteById")
    @ResponseBody
    public JsonResult delete(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        try {
            int effectRow = menuService.deleteById(id);
            if(effectRow > 0){
                return JsonResult.success("");
            } else {
                return JsonResult.failure("未能成功删除，请刷新查看数据是否存在");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    @GetMapping("/queryAll")
    @ResponseBody
    public JsonResult queryAll(){
        try {
            List<Menu> list = menuService.queryAll();
            return JsonResult.success(list);
        } catch (SQLException e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

}
